package com.crl.rcdp.sys.dao;

import com.cars.util.page.PageUtil;
import com.crl.dao.BaseDao;
import com.crl.rcdp.sys.model.SysApi;
import com.crl.rcdp.sys.vo.SysApiSearchVO;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @description:
 * @author: 孔垂云
 * @version: 1.0
 * @date: 2020/7/12 11:23
 */
@Repository
public class SysApiDao extends BaseDao<SysApi, SysApiSearchVO> {


    /**
     * 查询全部
     */
    public List<SysApi> list(SysApiSearchVO sysApiSearchVO) {
        String sql = "SELECT t.*,(select  name from TD_SYS_APITYPE where id=t.type_id) typeName FROM td_sys_api t where 1=1 ";
        sql += createSQL(sysApiSearchVO);
        sql += " order by created_at";
        sql = PageUtil.createMysqlPageSql(sql, sysApiSearchVO.getPage());
        return list(sql, sysApiSearchVO);
    }

    /**
     * 增加API
     */
    public int add(SysApi sysApi) {
        String sql = "INSERT INTO td_sys_api (name,type_id,url,remarks,display_order,request_type,created_by,created_at)" +
                " VALUES(:name,:typeId,:url,:remarks,:displayOrder,:requestType,:createdBy,now())";
        return insertForId(sql, sysApi, "id");
    }

    /**
     * 根据APIid删除
     */
    public int delete(Integer id) {
        String sql = "DELETE FROM td_sys_api WHERE id=?";
        return update(sql, id);
    }

    /**
     * 根据APIid修改
     */
    public int update(SysApi sysApi) {
        String sql = "UPDATE td_sys_api SET name=:name,type_id=:typeId,url=:url,remarks=:remarks,display_order=:displayOrder,request_type=:requestType,modified_by=:modifiedBy,modified_at=now() WHERE id=:id ";
        return update(sql, sysApi);
    }

    /**
     * 统计查询数据条数
     */
    public int count(SysApiSearchVO sysApiSearchVO) {
        String sql = "SELECT COUNT(id) FROM td_sys_api WHERE 1=1 ";
        sql += createSQL(sysApiSearchVO);
        return count(sql, sysApiSearchVO);
    }

    /**
     * 拼接查询条件
     */
    private String createSQL(SysApiSearchVO sysApiSearchVO) {
        String sql = "";
        if (sysApiSearchVO.getTypeId() != null) {
            sql += " and type_id=:typeId";
        }
        return sql;
    }

    /**
     * 根据id查询
     */
    public SysApi get(Integer id) {
        String sql = "SELECT t.*,(select  name from TD_SYS_APITYPE where id=t.type_id) typeName FROM td_sys_api t WHERE id=?";
        return get(sql, id);
    }

    /**
     * 根据id获取下级节点个数
     */
    public int getChildrenCount(Integer parentId) {
        String sql = "SELECT COUNT(id) FROM td_sys_api WHERE parent_id=?";
        return count(sql, parentId);
    }

    /**
     * 获取所有资源列表
     */
    public List<SysApi> listAll() {
        String sql = "SELECT * FROM td_sys_API WHERE 1=1 ORDER BY display_order";
        return list(sql);
    }
}